package com.barbarosso.video.model {
	import flash.display.MovieClip;	
	
	import nl.demonsters.debugger.MonsterDebugger;
	
	import com.barbarosso.video.constants.VideoConst;
	
	import org.openvideoplayer.events.OvpEvent;
	import org.openvideoplayer.net.OvpConnection;
	import org.openvideoplayer.net.OvpNetStream;
	import org.puremvc.as3.multicore.patterns.proxy.Proxy;
	
	import flash.events.NetStatusEvent;	

	/**
	 * @author barbarosso
	 */
	public class VideoProxy extends Proxy {

		public static const NAME 	: String = "com.barbarosso.video.model.VideoProxy";

		private var first			: Boolean = true;
        private var _nc				: OvpConnection;
        private var _ns 			: OvpNetStream;
		private var _nsProgress 	: Number;
		        
        private var duration		: String;
        private var domain			: String;
        private var url				: String ;
        
		//private var domain			: String = null;
//        private var url				: String = "http://products.edgeboss.net/download/products/content/demo/video/oomt/elephants_dream_700k.flv";

//        private var domain		: String = 'cp67126.edgefcs.net/ondemand';
//        private var filename		: String = 'mp4:mediapm/ovp/content/demo/video/elephants_dream/elephants_dream_768x428_24.0fps_408kbps.mp4';
       
        /**
         * constructor ******************************************************************************************
         */    
		public function VideoProxy(proxyName : String = null, data : Object = null) {
			super(proxyName, data);
		}
		
		/**
         * public Methods******************************************************************************************
         */
         public function setVideo(p_url : String , p_domain : String  = null , p_autoPlay : Boolean = true ) : void {
         	domain = p_domain;
         	url = p_url;
         	if(_nc == null){
	         	setupConnection();
         	}
         	if(p_autoPlay){
	         	play();
         	}
		}
		
		/**
         * protected Methods******************************************************************************************
         */
		protected function setupConnection():void {
            _nc = new OvpConnection();
            _nc.addEventListener(OvpEvent.ERROR, errorHandler);
            _nc.addEventListener(NetStatusEvent.NET_STATUS, con_nstatusHandler);
            _nc.connect(domain);
        }
        
        protected function setupNetstream() : void {
        	_ns = new OvpNetStream(_nc);
                _ns.addEventListener(OvpEvent.ERROR, errorHandler);
                _ns.addEventListener(NetStatusEvent.NET_STATUS, streamStatusHandler);
                _ns.addEventListener(OvpEvent.NETSTREAM_METADATA, streamMetadataHandler);
                _ns.addEventListener(OvpEvent.PROGRESS, streamProgressHandler);
                _ns.addEventListener(OvpEvent.COMPLETE, streamCompleteHandler);
        }
        
        protected function play():void {
			if (first) {
                first = false;
                //in an awesome API decision the play() command actually loads the video (and also plays it)
                _ns.play(url);
            } else {
                //don't use play() to play/pause, use togglePause()
                _ns.togglePause();
             }
		}
        
        /**
         * event Handlers ******************************************************************************************
         */
        private function errorHandler(e:OvpEvent):void {
            MonsterDebugger.trace(this,'ERROR #' + e.data["errorNumber"] + ': ' + e.data["errorDescription"]);
        }

        private function con_nstatusHandler(e:NetStatusEvent):void {
			MonsterDebugger.trace(this,'CONN_STATUS: ' + e.info["code"]);
			setupNetstream();
        }

        private function streamStatusHandler(e:NetStatusEvent):void {
            MonsterDebugger.trace(this,'STREAM_STATUS: ' + e.info["code"]);
			sendNotification(VideoConst.NS_CONNECTED );
        }

        private function streamMetadataHandler(e:OvpEvent):void {
            for (var key:String in e.data) {
				MonsterDebugger.trace(this,"STREAM_METADATA: " + key + "=" + e.data[key]);
            }
            duration = _nc.streamLengthAsTimeCode(e.data["duration"]);
        }

        private function streamProgressHandler(e:OvpEvent):void {
            //OvpNetStream throws out nice progress event, so update the scrubber and time display
            _nsProgress = _ns.bytesLoaded / _ns.bytesTotal * 100;
            sendNotification(VideoConst.STREAM_PROGRESS);
            //MonsterDebugger.trace(this,percentLoaded + "% loaded from a total of " + _ns.bytesTotal);
			
		}

		private function streamCompleteHandler(e:OvpEvent):void {
            //all done, so rewind to the beginning
            _ns.pause();
            _ns.seek(0);
        }
		/*
		 * setters and getters methods ----------------------------------------------
		 */ 
	 
	 /**
	  * read only
	  */
		public function get ns (  ) : OvpNetStream {
			return _ns  ;
		};

		public function get nsProgress(  ) : Number {
			return _nsProgress  ;
		};
			
	}
}
